<template>
  <div>
    <!--背景画布-->
    <PageWrapper contentBackground contentClass="p-4">
      <!--标签页-->
      <Tabs :animated="true">
        <TabPane v-for="item in navBarList" :key="item.key">
          <!--使用插槽为标签页添加图标-->
          <template #tab>
            <Icon :icon="item.icon" />
            {{ item.name }}
          </template>
          <!--首页-->
          <BasicForm @register="homePageRegisterForm" v-if="item.key === 'home'">
            <template #homeSettingsSlot>
              <Button type="primary" @click="homeSaveClick" :disabled="isHomeSaveFlag">保存</Button>
            </template>
          </BasicForm>
          <!--通知-->
          <BasicForm @register="noticeRegisterForm" v-if="item.key === 'notice'">
            <template #slackSettingsSlot>
              <Button type="primary" @click="noticeSaveClick" :disabled="isNoticeSaveFlag">
                保存
              </Button>
            </template>
          </BasicForm>
          <!--仓库-->
          <SettingWarehouse v-if="item.key === 'repository'" :isSetting="true" />
          <!--自动提交-->
          <SettingWarehouse
            v-if="item.key === 'autoCommit' && !userStore.getHasRepository"
            :isSetting="true"
          />
          <AutoCommit v-if="item.key === 'autoCommit' && userStore.getHasRepository" />
        </TabPane>
      </Tabs>
    </PageWrapper>
  </div>
</template>
<script lang="ts" setup>
  import { navBarList } from './components/setting.data';
  import { PageWrapper } from '/@/components/Page';
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { Tabs, TabPane } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ref, onMounted } from 'vue';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { homeSettingParams as homeSettingParams } from '/@/api/thingsborad/settings/model/settingsModel';
  import SettingWarehouse from '/@/components/thingsborad/sharedComponents/modules/SettingWarehouse.vue';
  import { Button } from 'ant-design-vue';
  import {
    getHomePageSettings,
    getInfoData,
    saveTheHomeSetting,
    saveInfoData,
    getNotificationSettings,
    editNotificationSettings,
  } from '/@/api/thingsborad/settings/settings';
  import AutoCommit from './components/AutoCommit.vue';
  import { useSystemStoreWithOut } from '/@/store/modules/thingsboard/systemParams';

  const userStore = useSystemStoreWithOut();

  const { createMessage } = useMessage();
  let homeParams = ref<homeSettingParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'title',
    sortOrder: 'ASC',
  });
  let isHomeSaveFlag = ref<boolean>(true);
  let isNoticeSaveFlag = ref<boolean>(true);
  onMounted(() => {
    //
    getHomeSelectData();
    //
    notificationSettings();
  });
  // 表单内容 首页
  const homePageSchemas: FormSchema[] = [
    {
      field: 'homeSettings',
      component: 'CheckboxGroup',
      label: '首页设置',
      colProps: {
        span: 24,
      },
      componentProps: {
        onClick: () => {
          isHomeSaveFlag.value = false;
        },
        options: [
          {
            label: '隐藏首页仪表板工具栏',
            value: 'hideToolbar',
          },
        ],
      },
    },
    {
      field: 'homeDashboard',
      component: 'Select',
      label: '首页仪表板',
      colProps: {
        span: 12,
      },
      componentProps: {
        listHeight: 160,
        onClick: () => {
          isHomeSaveFlag.value = false;
        },
      },
    },
    {
      field: 'homeSettingsButton',
      component: 'Input',
      slot: 'homeSettingsSlot',
      label: '',
      colProps: {
        span: 24,
      },
    },
  ];
  //表单注册 首页
  const [
    homePageRegisterForm,
    { updateSchema: homeUpdateSchema, validate: homeValidate, setFieldsValue: homeSetFieldsValue },
  ] = useForm({
    layout: 'vertical',
    schemas: homePageSchemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
  });
  // 表单内容 通知
  const noticeSchemas: FormSchema[] = [
    {
      field: 'SlackSettings',
      component: 'Input',
      label: 'Slack 设置',
      colProps: {
        span: 12,
      },
      componentProps: {
        placeholder: '请输入Slack API令牌',
        onClick: () => {
          isNoticeSaveFlag.value = false;
        },
      },
    },
    {
      field: 'slackSettingsButton',
      component: 'Input',
      slot: 'slackSettingsSlot',
      label: '',
      colProps: {
        span: 24,
      },
    },
  ];
  //表单注册 通知
  const [noticeRegisterForm, { validate: noticeValidate, setFieldsValue: noticeSetFieldsValue }] =
    useForm({
      layout: 'vertical',
      schemas: noticeSchemas,
      actionColOptions: {
        span: 24,
      },
      showActionButtonGroup: false,
    });

  async function getHomePageData(_params: homeSettingParams) {
    try {
      let paramsFlag: any = {
        pageSize: 10,
        page: 0,
        sortProperty: 'title',
        sortOrder: 'ASC',
      };
      const HomePageSettings = await getHomePageSettings(paramsFlag);
      const homeValidateValue = await homeValidate();
      let data: any;

      data = {
        dashboardId:
          homeValidateValue.homeDashboard === undefined ? null : HomePageSettings.data[0].id,
        hideDashboardToolbar: homeValidateValue.homeSettings.length === 0 ? false : true,
      };

      await saveInfoData(data);
      let options = ref<Array<any>>([]);
      HomePageSettings.data.forEach((item) => {
        options.value.push({
          label: item.name,
          value: item.name,
        });
      });
      homeUpdateSchema({
        field: 'homeDashboard',
        componentProps: {
          options: options.value,
        },
      });
    } catch (error) {}
  }
  // 是否初始化数据
  async function getHomeSelectData() {
    try {
      const infoData = await getInfoData();
      if (infoData.hideDashboardToolbar) {
        homeSetFieldsValue({
          homeSettings: 'hideToolbar',
        });
      }
      if (infoData.dashboardId !== null) {
        const homeSettingValue = await saveTheHomeSetting(infoData.dashboardId.id);
        homeSetFieldsValue({
          homeDashboard: homeSettingValue.title,
        });
      }
      getHomePageData(homeParams.value);
    } catch (error) {}
  }
  async function homeSaveClick() {
    try {
      const homeValidateValue = await homeValidate();
      if (homeValidateValue.homeDashboard !== undefined) {
        homeParams.value.textSearch = homeValidateValue.homeDashboard;
      }
      await getHomePageData(homeParams.value);
      createMessage.success('首页仪表板保存成功');
    } catch (error) {}
  }

  async function notificationSettings() {
    try {
      const notificationSettingsData = await getNotificationSettings();
      if ('SLACK' in notificationSettingsData.deliveryMethodsConfigs) {
        noticeSetFieldsValue({
          SlackSettings: notificationSettingsData.deliveryMethodsConfigs.SLACK.botToken,
        });
      }
    } catch (error) {}
  }

  async function noticeSaveClick() {
    try {
      const noticeValidateValue = await noticeValidate();

      let data: any = {
        deliveryMethodsConfigs: {
          SLACK: {
            method: 'SLACK',
            botToken: noticeValidateValue.SlackSettings,
          },
        },
      };
      await editNotificationSettings(data);
      createMessage.success('Slack设置保存成功');
    } catch (error) {}
  }
</script>
